package com.kanshu.model;

import java.io.*;
import java.net.Socket;
/**
 * @author GAIst
 * ClassName SocketUser.java
 * From
 * Description OK
 * createTime 2024年12月20日14:32:26
 */
public class SocketUser {
    Socket socket = new Socket("localhost", 9527);
    OutputStream os = socket.getOutputStream();
    InputStream is = socket.getInputStream();
    ObjectOutputStream oos = new ObjectOutputStream(os);
    ObjectInputStream ois = new ObjectInputStream(is);

    public SocketUser() throws IOException {

    }
    public <V> Object send(V v) throws IOException {
        Object response = null;
        if (v != null) {
            // 将用户信息发送给服务器
            try {
                oos.writeObject(v);
                oos.flush();
                // 接收服务器响应
                response = ois.readObject();
                if (response == null) {
                    System.out.println("无返回");
                }
                System.out.println(response);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return response;
    }

    public <V> Object downloadSend(V v) throws IOException {
        Object response = null;
        if (v != null) {
            // 将用户信息发送给服务器
            try {
                oos.writeObject(v);
                oos.flush();
                // 接收服务器响应
                response = ois.readObject();
                if (response == null) {
                    System.out.println("无返回");
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return response;
    }

    public void sendExit(){
        try {
            oos.writeObject("EXIT");
            oos.flush();
            socket.close();
        }catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void allClose() throws IOException {
        oos.close();
        ois.close();
        is.close();
        os.close();
        socket.close();
    }

}
